# -*- coding: utf-8 -*-

from django.db import models
from django.db.models import Q
from rest_framework import serializers
from rest_framework.exceptions import ValidationError


class TargetsReadOnly(object):
    def __init__(self, *targets):
        self.targets = targets

    def __getattr__(self, name):
        count = len(self.targets)
        while count:
            target = self.targets[count - 1]
            try:
                return getattr(target, name)
            except:
                try:
                    return target[name]
                except:
                    pass
            count -= 1
        return super(TargetsReadOnly, self).__delattr__(name)

    def __getitem__(self, name):
        return self.__getattr__(name)


class BaseSerializer(serializers.ModelSerializer):
    """基础模板表"""

    def to_representation(self, instance):
        ret = super(BaseSerializer, self).to_representation(instance)

        # # just for dbug
        # ret = OrderedDict()
        # fields = self._readable_fields

        # for field in fields:
        #     try:
        #         info("field name: ======>{}".format(field.field_name))
        #         attribute = field.get_attribute(instance)
        #     except SkipField:
        #         continue

        #     # We skip `to_representation` for `None` values so that fields do
        #     # not have to explicitly deal with that case.
        #     #
        #     # For related fields with `use_pk_only_optimization` we need to
        #     # resolve the pk value.
        #     check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute
        #     if check_for_none is None:
        #         ret[field.field_name] = None
        #     else:
        #         ret[field.field_name] = field.to_representation(attribute)

        date_time_fields = [
            'create_time',
            'update_time'
        ]
        for name in date_time_fields:
            if hasattr(instance, name) and getattr(instance, name):
                ret[name] = getattr(instance,
                                    name).strftime('%Y-%m-%d %H:%M:%S')
        return ret
